import threading
from datetime import datetime

from flask import Blueprint, jsonify, request
from sqlalchemy import desc

from applications.extensions import db
from applications.models import SignsData2, News, Estimate

admin_message_push = Blueprint('adminMessagePush', __name__, url_prefix='/push')

# 接收课题四训练开始消息推送
@admin_message_push.post('/news')
def get_news():
    thread = threading.Thread(target=insert_news,args=(request.json,))
    thread.run()
    return jsonify(code=200, msg="OK")

# 接收课题四结束消息和得分评估
@admin_message_push.post('/estimate')
def get_estimate_score():
    thread = threading.Thread(target=insert_estimate,args=(request.json,))
    thread.run()
    return jsonify(code=200, msg="OK")

# 接收体征信息
@admin_message_push.post('/vital_signs')
def get_vital_signs():
    datas = request.json['datas']
    thread = threading.Thread(target=insert_signs, args=(datas,))
    thread.run()
    return jsonify(code=200, msg="OK", data=None)

def insert_news(data: dict) -> None:
    kind = data.get('kind')
    alarm_type = data.get('alarm_type')
    name = data.get('name')
    sn = data.get('sn')
    content = data.get('content')
    occur_time = data.get('ts')
    rtsp = data.get('rtsp')
    news = News(kind = kind,alarm_type=alarm_type,name=name,sn=sn,content=content,occur_time=occur_time,rtsp=rtsp)
    db.session.add(news)
    db.session.commit()

def insert_estimate(data:dict) -> None:
    kind = data.get('kind')
    type = data.get('type')
    name = data.get('name')
    work_score = data.get('work_score')
    process_score = data.get('process_score')
    staff_score = data.get('staff_score')
    cal_result = data.get('cal_result')
    occur_time = data.get('ts')
    estimate = Estimate(kind=kind, type=type, name=name, work_score=work_score, process_score=process_score,
                        staff_score=staff_score, cal_result=cal_result, occur_time=occur_time)
    news = News.query.order_by(desc('occur_time')).limit(1).one()
    news.status = 2
    db.session.add(estimate)
    db.session.commit()


def insert_signs(datas: list) -> None:
    for data in datas:
        user_name = data.get('police_name')
        user_id = data.get('police_code')
        heart_rate_time = data.get('heart_rate_time')
        heart_rate = data.get('heart_rate')
        temp_time = data.get('temp_time')
        temperature = data.get('temperature')
        sn = data.get('sn')
        record = SignsData2(user_id=user_id, user_name=user_name, heart_rate_time=heart_rate_time, heart_rate=heart_rate, \
                        temp_time=temp_time, temperature=temperature, sn=sn)
        db.session.add(record)
        db.session.commit()
